lh.cache.amList = [];
$(function(){
	initPage();
	initData();
	loadAuctionMicro();//加载专场
	lh.scrollBottom(loadAuctionMicro);//下拉加载更多数据
});

function initPage(){
	$('.sstext').click(function () {
	    var id = $(this).attr('id');
	    if ($(this).text().trim() == '藏品') {
	        $(this).html('商铺&nbsp;<img src="/images/front/top_img5.png" width="5" height="4" />');
	        $('#' + id + '_input').attr('placeholder', '输入商铺名称');
	    } else {
	        $(this).html('藏品&nbsp;<img src="/images/front/top_img5.png" width="5" height="4" />');
	        $('#' + id + '_input').attr('placeholder', '输入藏品名称');
	    }
	})
	$('#bottom_menu_as').off('click');
	$('#bottom_menu_as').click(function(){
		lh.jumpR('/addGoods?from=am');
	});
	$('#bottom_menu_name_as').text('发布');
	
	/*countDown("2018/8/10 23:59:59", "#demo02 .day", "#hour2", "#minute2", "#second2");
	countDown("2018/8/10 23:59:59", "#demo01 .day", "#hour1", "#minute1", "#second1");*/
	
	lh.plugins.template = $('#template').html();
	Mustache.parse(lh.plugins.template);   // optional, speeds up future uses
	
	lh.plugins.templateOffers = $('#template_offers').html();
	Mustache.parse(lh.plugins.templateOffers);   // optional, speeds up future uses
}

function initData(){
	
}

function countDown(auctionId, seconds, hour_elem, minute_elem, second_elem) {
    var timer = setInterval(function () {
        if (seconds > 0) {
            seconds --;
            /*var day = Math.floor((sys_second / 3600) / 24);*/
            var hour = Math.floor(seconds / 3600);
            var minute = Math.floor((seconds / 60) % 60);
            var second = Math.floor(seconds % 60);
            $(hour_elem).text(hour < 10 ? "0" + hour : hour);//计算小时
            $(minute_elem).text(minute < 10 ? "0" + minute : minute);//计算分
            $(second_elem).text(second < 10 ? "0" + second : second);// 计算秒
        } else {
            clearInterval(timer);
        	auctionOver(auctionId);
        }
    }, 1000);
    if(seconds == 0){
    	$('#am_'+auctionId).remove();//时间结束时移除
    }
}

function loadAuctionMicro(){
	$('#resultTip').hide();
	$('#loadingTip').show();
	var param = {page:lh.page.currentPage, rows:lh.page.rows};
	//var userId = lh.param.userId;
	var auctionId = lh.param.auctionId;
	//if(userId)param.userId = userId;
	if(auctionId)param.auctionId = auctionId;
	lh.post('front', '/getAuctionMicroList', param, function(rsp){
		$('#loadingTip').hide();
		if(rsp.success){
			var data = rsp.rows;
			if(data && data.length>0){
				makeAuctionMicroDom(data, true);
				lh.page.currentPage ++;
			}else{
				$('#resultTip').text('没有更多数据').show();
			}
		}else{
			lh.page.currentPage = 1;
			$('#resultTip').text(rsp.msg).show();
		}
	},'json');
}

function makeAuctionMicroDom(data, isAppend){
	for(var i = 0; i<data.length; i++){
		var am = data[i];
		if(am.userAvatar){
			//TODO
			//am.userAvatar += '@50h_50w_1e'; //OSS图片
		}else{
			am.userAvatar = '/images/front/default_avatar.png';
		}
		lh.cache.amList = _.concat(lh.cache.amList, data);
		var asoAry = am.asoList;
		if(asoAry && asoAry.length > 0){
			for(var j = 0; j < soAry.length; j++){
				var aso = asoAry[j];
				if(aso.userAvatar){
					aso.userAvatar += '@50h_50w_1e'; 
				}else{
					aso.userAvatar = '/images/front/default_avatar.png';
				}
				aso.offerAt = moment().from(aso.offerAt); 
				if(aso.offerPrice == asgObj.offerPrice){
					aso.priceLead = 1;
				}
			}
		}
		if(am.postageFee == 2){
			asgObj.postageFee = "";
		}
		if(am.isSevenReturn == 2){
			asgObj.isSevenReturn = "";
		}
		if(data[i].creditMargin == 0){
			data[i].creditMargin = "";
		}
		var auctionId = am.id;
		autoRefreshOffer(auctionId);//自动定时刷新出价
		countDown(auctionId, am.remainSeconds, '#ctdown_hour_'+auctionId, '#ctdown_minute_'+auctionId, '#ctdown_second_'+auctionId);
	}
	var data = {
		rows:data,
		picsDom:function(){
			var goodsPicPaths = this.goodsPicPaths;
			if(!goodsPicPaths)return '';
			var pics = goodsPicPaths.split(',');
			var length = pics.length;
			if(length > 9)length = 9;
			var picsDom = '';
			for(var i=0;i<length;i++){
				var pic = pics[i];
				//TODO
				//pic += '@120h_120w_1e_1c_50Q'; //OSS图片@100h_100w_1e_1c
				picsDom += '<li style="width:32%;margin:1px;max-height:120px;overflow:hidden;"><img src="'+pic+'" style=""/></li>';
			}
			return picsDom;
		},
		picsUrlsDom:function(){
			var goodsPicPaths = this.goodsPicPaths;
			if(!goodsPicPaths)return '';
			var pics = goodsPicPaths.split(',');
			var length = pics.length;
			var picsUrl = pics;
			var picsUrlsDom = '';
			for(var j=0;j<length;j++){
				//TODO
				//picsUrl[j] = "'"+picsUrl[j]+"@640w_50Q'";//OSS图片
				picsUrl[j] = "'"+picsUrl[j]+"'";
			}
			picsUrlsDom = 'onclick="scanPic(['+picsUrl+'])"';
			return picsUrlsDom;
		},
		/*picNum:function(){
			var goodsPicPaths = this.asg.goodsPicPaths;
			var pics = goodsPicPaths.split(',');
			var length = pics.length;;
			if(length > 9)length = 9;
			return length;
		},*/
		date:function(){
			var createdAt = this.createdAt;
			createdAt = lh.formatDate(createdAt);
			return createdAt;
		},
		focusDom:function(){
			var overFoucs = this.overFoucs;
			var focusDom = '<a href="javascript:void(0);" role="1" id="userFocus_id_'+this.userId+'" class="a_gz" onclick="doFocus('+this.userId+');return false;">+关注</a>';
			if(overFoucs && overFoucs > 0){
				focusDom = '<a href="javascript:void(0);" role="2" id="userFocus_id_'+this.userId+'" class="a_qxgz" onclick="doFocus('+this.userId+');return false;">取消关注</a>';
			}
			return focusDom;
		}
    }
	var rendered = Mustache.render(lh.plugins.template, data);
	//isAppend = false;//临时
	if(isAppend){
		$('#auctionMicroList').append(rendered);
	}else{
		$('#auctionMicroList').html(rendered);
	}
}

function doFocus(userId){
	if(!userId)return;
	var role = $('#userFocus_id_'+userId).attr('role');
	if(role == 1){
		 focusUser(userId);
	}else{
		unFocusUser(userId);
	}
}

function focusUser(userId){
	lh.post('front', '/addOrUpdateFans', {userId:userId},function(rsp){
		frontLoginCheck(rsp);//登陆检查 
		if(rsp.success){
			$('#userFocus_id_'+userId).removeClass('a_gz').addClass('a_qxgz').text('取消关注').attr('role',2);
		}
	},'json');
}

function unFocusUser(userId){
	lh.post('front', '/deleteFans', {userId:userId},function(rsp){
		frontLoginCheck(rsp);//登陆检查 
		if(rsp.success){
			$('#userFocus_id_'+userId).removeClass('a_qxgz').addClass('a_gz').text('+关注').attr('role',1);
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function doBid(){
	var price = $('#numView').text();
	$('#topPrice').val(price);
	doOffer('save');
	hideCallActionSheet();
}

function doOffer(operation, auctionId, bail){
	//	/currentOfferPrice
	if(operation == 'show'){
		$("#topPrice").val('');
		lh.current.auctionId = auctionId;
		lh.current.bail = bail;
		var price = $('#top_offer_'+auctionId).text();
		var increaseRangePrice = $('#increaseRangePrice_'+auctionId).val();
		if(!increaseRangePrice)increaseRangePrice = 20;
		price = price.replace('￥','').trim();
		price = new Number(price)
		increaseRangePrice = new Number(increaseRangePrice);
		var nextPrice = price + increaseRangePrice;
		showCallActionSheet({opt:'amBid', price:price, nextPrice:nextPrice});//call面板
	}else if(operation == 'cancel'){
		lh.current.auctionId = null;
		hideCallActionSheet();//call面板
	}else if(operation == 'save'){
		var auctionId = lh.current.auctionId;
		var bail = lh.current.bail;
		var buyoutPrice = lh.current.buyoutPrice;
		var r = $("#r").val();
		if(!auctionId || !auctionId)return;
		var offerPrice = $('#topPrice').val();
		if(!offerPrice || offerPrice <= 0){
			lh.alert('请输入您的出价');return;
		}
		var creditMoney = $('#creditMoney').val();
		var shopPrice = $('#shopPrice_'+asgId).val();
		var url = location.href;
		if(url.indexOf('?')>0){
			url += '&auctionId='+lh.current.auctionId;
		}else{
			url += '?auctionId='+lh.current.auctionId;
		}
		if(!checkAuctionMicroBail(bail, creditMoney, url, lh.current.asgId))return;
		if(buyoutPrice > 0 && offerPrice >= buyoutPrice){
			offerPrice = buyoutPrice;
		}
		lh.post('front', '/addAuctionMicroOffer',{auctionId:auctionId,auctionGoodsId:goodsId,offerPrice:offerPrice,promoteUserSerial:r},function(rsp){
			if(rsp.success){
				hideCallActionSheet();
				/*if(shopPrice == offerPrice){//一口价，直接跳往支付页面
					lh.jumpR('/user');
				}*/
			}else{
				lh.page.currentPage = 1;
				lh.alert(rsp.msg);
			}
			checkLastOffer(asgId, goodsId, auctionId);//刷新报价
		},'json');
	}
}

function autoRefreshOffer(auctionId){
	 var timer = setInterval(function () {
        checkLastOffer(auctionId);
    	/*if (sys_second > 0) {
            clearInterval(timer);
        }*/

    }, 50000);//每50秒刷新一次
}

function checkLastOffer(auctionId){
	if(!auctionId)return;
	lh.post('front', '/getAuctionMicroOffer',{auctionId:auctionId},function(rsp){
		if(rsp.success){
			var asoList = rsp.asoList;
			if(!asoList)return;
			var am = _.find(lh.cache.amList, {'id': auctionId});
			am.asoList = asoList;
			appendOffers(am);
		}
	},'json');
}

function appendOffers(am){
	var auctionId = am.id;
	var domOuterId = '#offer_container_'+auctionId;
	var asoList = am.asoList;
	var offerLength = asoList.length;
	if(offerLength > 0){
		for(var j = 0;j<offerLength;j++){
			var aso = asoList[j];
			aso.offerAt = moment().from(aso.offerAt); 
			if(aso.offerPrice == am.offerPrice){
				aso.priceLead = 1;
			}
		}
	}
	
	var topOfferId = '#top_offer_'+auctionId;
	var price = am.offerPrice || am.priceBegin || 0;
	$(topOfferId).text('￥' + price);
	$('#topPrice').val(price+20);//更新输入价格框，默认提高20元
	var rendered = Mustache.render(lh.plugins.templateOffers, {rows:asoList});
	$(domOuterId).html(rendered);
}

function auctionOver(auctionId){
	lh.post('front', '/finishAuctionMicro',{auctionId:auctionId},function(rsp){
		if(rsp.success){
			var remainSeconds = rsp.remainSeconds;
			if(remainSeconds){
				countDown(auctionId, remainSeconds, '#ctdown_hour_'+auctionId, '#ctdown_minute_'+auctionId, '#ctdown_second_'+auctionId);
			}else{
				$('#am_'+auctionId).remove();
			}
		}
	},'json');
}

function toggleDescription(id){
	var $dom = $('#desc_'+id);
	var r = $dom.attr('role');
	if(r == 1){
		$dom.css('height','auto');
		$dom.attr('role', 2);
		$('#desc_'+id+' a').text('缩略');
	}else{
		$dom.css('height','45px');
		$dom.attr('role', 1);
		$('#desc_'+id+' a').text('展开');
	}
}

function showShare(){
	$('#shareMask,#share').show();
}
function hideShare(){
	$('#shareMask,#share').hide();
}

function togglePraise(asgId, userId){
	var role = $('#praise_btn_'+asgId).attr('role');
	if(role == 1){
		addPraise(asgId, userId);
	}else{
		cancelPraise(asgId, userId);
	}
}

function addPraise(asgId, userId){
	var obj ={praiseType:2, praiseId:asgId};
	lh.post('front', '/addOrUpdateUserPraise', obj, function(rsp){
		frontLoginCheck(rsp);//登陆检查 
		if(rsp.success){
			$('#praise_btn_'+asgId).attr('role',2);
			//$('#praise_text_'+asgId).text('取消点赞');
			var praiseId = rsp.praiseId;
			var avatar = rsp.userAvatar;
			appendPraise(asgId, userId, praiseId, avatar);
		}
	},'json');
}

function cancelPraise(asgId, userId){
	if(!asgId)return;
	var obj ={praiseType:2, praiseObjId:asgId};
	lh.post('front', '/deleteUserPraise',obj,function(rsp){
		frontLoginCheck(rsp);//登陆检查 
		if(rsp.success){
			var praiseId = rsp.praiseId;
			$('#praise_'+praiseId).remove();
			$('#praise_btn_'+asgId).attr('role',1);
			//$('#praise_text_'+asgId).text('点赞');
		}
	},'json');
}

function appendPraise(asgId, userId, praiseId, avatar){
	var dom = 
	'<div id="praise_'+praiseId+'" class="li_day" style="height:60px;overflow:hidden;width:60px;">'+
		'<div class="t_0100_29" style="border:none;">'+
			'<div class="l_81">'+
				'<a href="javascript:jumptToUrl(\'/sale/'+userId+'\');"> <img src="'+avatar+'" width="100%" /></a>'+
			'</div>'+
		'</div>'+
	'</div>';
	$('#praise_container').prepend(dom);
	
}

function doBuyout(){
	
	
}

